<?php
declare (strict_types = 1);

namespace app\code\controller;

// +----------------------------------------------------------------------
// | mysql_tables()                查询数据库所有表信息
// | columns()                     查询某张表的所有字段
// | mokuai()                      获取所有模块名
// | index()                       首页
// | modular_page()                模块页面
// | create_modular()              自动创建模块
// | common_page()                 公共函数文件页面
// | middleware_page()             中间件页面
// | middleware_code()             中间件代码
// | create_middleware()           创建中间件文件
// | event_page()                  事件页面
// | event_code()                  事件代码
// | create_event()                创建事件文件
// | validata_page()               验证器页面
// | validata_page2()              验证器信息页面
// | validata_page3()              验证器代码页面
// | validata()                    组装验证器数据
// | _name()                       组装验证器数据
// | _getf()                       组装验证器数据
// | create_model_files()          创建模型文件
// | parseName()                   数据表名转换成符合命名规格的字符串
// +----------------------------------------------------------------------

use app\BaseController;
use think\App;
use think\facade\Db;
use think\facade\View;
use think\helper\Str;
class Index extends BaseController
{
    public $modular_name;

    /**
     * 构造方法
     * Index constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        $this->modular_name = App('http')->getName();
        parent::__construct($app);
    }

    public function table1(){
        return View::fetch();
    }
    public function form1(){
        return View::fetch();
    }
    /**
     * 空控制器
     */
    public function empty_controller(){
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'empty_controller.stub');
        View::assign('content',$content);
        return View::fetch();
    }
    /**
     * 控制器页面
     */
    public function basis_controller(){
        View::assign('mokuai',$this->mokuai());
        View::assign('tables',$this->mysql_tables());
        return View::fetch();
    }

    /**
     * 创建控制器
     */
    public function create_controller(){
        $controller_name = input('controller_name');
        $name = ucfirst($controller_name);
        if(empty($controller_name)){
            $this->error('缺少控制器名');
        }
        $mokuai = input('mokuai');
        $function_name = input('function_name');
        $logic = input('logic');
        $function_name = empty($function_name) ? $controller_name:$function_name;
        $mokuai = empty($mokuai) ? 'index':$mokuai;
        if(empty($mokuai)){
            $modular ="";
            $dir = 'controller';
            $files = [
                '__file__'   => [$name.".php"],
            ];
        }else{
            $modular = $mokuai."\\";
            $dir = $mokuai;
            $files = [
                '__dir__'    => ['controller'],
                'controller'=>[$name]
            ];
        }
        if($logic){
            $logic1 = "use app\\".$modular."logic\\".$logic." as ".$logic."Logic;";
            $new = '$this->logic = new '.$logic.'Logic();';
        }else{
            $logic1 = '';
            $new = '';
        }
        $resources = input('resources');
        if(!$resources){
            //基本控制器
            $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'controller.stub');
            $content = str_replace(
                [
                    '{%name%}',
                    '{%modular%}',
                    '{%function_name%}',
                    '{%logic%}',
                    '{%name1%}',
                    '{%new%}',
                ],
                [
                    $controller_name,
                    $modular,
                    $function_name,
                    $logic1,
                    $name,
                    $new,
                ],
                $content
            );
            $text = '创建基础控制器完成';
        }else{
            //资源控制器
            $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'resources.stub');
            $content = str_replace(
                [
                    '{%name%}',
                    '{%modular%}',
                    '{%function_name%}',
                    '{%logic%}',
                    '{%name1%}',
                    '{%new%}',
                ],
                [
                    $controller_name,
                    $modular,
                    $function_name,
                    $logic1,
                    $name,
                    $new,
                ],
                $content
            );
            $text = '创建资源控制器完成';
        }
        $Build = new \demo\MyBuild();
        $Build->execute($dir, $files, $content);
        $this->success($text);
    }


    /**
     * 创建分层文件
     */
    public function layered_files1(){
        $data = input('param.');
        $mokuai = $data['mokuai'];
        if(!empty($data['table'])){
            //一个模型文件
            $cls = $this->columns($data['table']);
            $res =  $this->timestamp($cls);
            $table = $data['table'];
            $table1 = $table;
            $name = $this->parseName($table, 1);
            //数据层
            if(empty($mokuai)){
                $modular ="";
                $dir = 'logic';
                $files = [
                    '__file__'   => [$name.".php"],
                ];
            }else{
                $modular = $mokuai."\\";
                $dir = $mokuai;
                $files = [
                    '__dir__'    => ['logic'],
                    'logic'=>[$name]
                ];
            }
            //模型表
            $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'logic.stub');
            $content = str_replace(
                [
                    '{%name%}',
                    '{%modular%}',
                    '{%binding_table%}',
                    '{%id%}',
                    '{%disuse%}',
                    '{%scope%}',
                    '{%json%}',
                    '{%readonly%}',
                    '{%time%}',
                ],
                [
                    $name,
                    $modular,
                    $table1,
                    $res['key'],
                    $res['disuse'],
                    $res['scope'],
                    $res['json'],
                    $res['readonly'],
                    $res['time'],
                ],
                $content
            );
            $Build = new \demo\MyBuild();
            $Build->execute($dir, $files, $content);
            $this->success('创建分层文件完成');
        }
        else{
            //全部文件
            $tables = $this->mysql_tables();
            //数据层
            foreach ($tables as $v){
                $cls = $this->columns($v['Name']);
                $res =  $this->timestamp($cls);
                $table = $v['Name'];
                $table1 = $table;
                $name = $this->parseName($table, 1);
                $tablename = $this->table($v['Name']);
                if(empty($mokuai)){
                    $modular ="";
                    $dir = 'logic';
                    $files = [
                        '__file__'   => [$name.".php"],
                    ];
                }else{
                    $modular = $mokuai."\\";
                    $dir = $mokuai;
                    $files = [
                        '__dir__'    => ['logic'],
                        'logic'=>[$name]
                    ];
                }
                //模型表
                $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'logic.stub');
                $content = str_replace(
                    [
                        '{%name%}',
                        '{%modular%}',
                        '{%binding_table%}',
                        '{%id%}',
                        '{%disuse%}',
                        '{%scope%}',
                        '{%json%}',
                        '{%readonly%}',
                        '{%time%}',
                    ],
                    [
                        $name,
                        $modular,
                        $table1,
                        $res['key'],
                        $res['disuse'],
                        $res['scope'],
                        $res['json'],
                        $res['readonly'],
                        $res['time'],
                    ],
                    $content
                );
                $Build = new \demo\MyBuild();
                $Build->execute($dir, $files, $content);
            }
            $this->success('创建所有表的分层文件完成');
        }
    }

    /**
     * 分层文件
     */
    public function layered_files(){
        View::assign('mokuai',$this->mokuai());
        View::assign('tables',$this->mysql_tables());
        return View::fetch();
    }
    /**
     * 创建分层代码
     */
    public function layered_code(){
        View::assign('mokuai',$this->mokuai());
        View::assign('tables',$this->mysql_tables());
        View::assign('type',0);
        return View::fetch();
    }
    /**
     * 分层代码
     */
    public function layered_code1(){
        $data = input('param.');
        $mokuai = $data['mokuai'];
        $cls = $this->columns($data['table']);
        $res =  $this->timestamp($cls);
        $table = $data['table'];
        $table1 = $table;
        $name = $this->parseName($table, 1);
        if(empty($mokuai)){
            $modular ="";
        }else{
            $modular = $mokuai."\\";
        }
        //模型表
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'logic.stub');
        $content = str_replace(
            [
                '{%name%}',
                '{%modular%}',
                '{%binding_table%}',
                '{%id%}',
                '{%disuse%}',
                '{%scope%}',
                '{%json%}',
                '{%readonly%}',
                '{%time%}',
            ],
            [
                $name,
                $modular,
                $table1,
                $res['key'],
                $res['disuse'],
                $res['scope'],
                $res['json'],
                $res['readonly'],
                $res['time'],
            ],
            $content
        );
        View::assign('content',$content);
        View::assign('type',1);
        return View::fetch('layered_code');
    }
    /**
     * 创建模型代码
     */
    public function create_model_code(){
        View::assign('mokuai',$this->mokuai());
        View::assign('tables',$this->mysql_tables());
        View::assign('type',0);
        return View::fetch();
    }
    public function create_model_code1(){
        $data = input('param.');
        $mokuai = $data['mokuai'];
        $modelLayer = input('modelLayer');
        if(!empty($data['table'])){
            //一个模型文件
            $cls = $this->columns($data['table']);
            $res =  $this->timestamp($cls);
            $table = $data['table'];
            $table1 = $table;
            $name = $this->parseName($table, 1);
            if($modelLayer == 'model'){
                //数据层
                if(empty($mokuai)){
                    $modular ="";
                    $dir = 'model';
                    $files = [
                        '__file__'   => [$name.".php"],
                    ];
                }else{
                    $modular = $mokuai."\\";
                    $dir = $mokuai;
                    $files = [
                        '__dir__'    => ['model'],
                        'model'=>[$name]
                    ];
                }
                $tablename = $this->table($table);
                if(strstr($tablename, '中间表') || strstr($tablename, '关联表')){
                    //中间表
                    $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'piovt.stub');
                    $content = str_replace(
                        [
                            '{%name%}',
                            '{%modular%}',
                        ],
                        [
                            $name,
                            $modular,
                        ],
                        $content
                    );
                }else{
                    //模型表
                    $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'model.stub');
                    $content = str_replace(
                        [
                            '{%name%}',
                            '{%modular%}',
                            '{%binding_table%}',
                            '{%id%}',
                            '{%disuse%}',
                            '{%scope%}',
                            '{%json%}',
                            '{%readonly%}',
                            '{%time%}',
                        ],
                        [
                            $name,
                            $modular,
                            $table1,
                            $res['key'],
                            $res['disuse'],
                            $res['scope'],
                            $res['json'],
                            $res['readonly'],
                            $res['time'],
                        ],
                        $content
                    );
                }
            }
        }
        else{
            //全部模型文件
            $tables = $this->mysql_tables();
            if($modelLayer == 'model'){
                //数据层
                foreach ($tables as $v){
                    $cls = $this->columns($v['Name']);
                    $res =  $this->timestamp($cls);
                    $table = $v['Name'];
                    $count = strpos($table,config('database.connections.mysql.prefix'));
                    $table1 = substr_replace($table,"",$count,strlen(config('database.connections.mysql.prefix')));
                    $name = $this->parseName($table, 1);
                    $tablename = $this->table($v['Name']);
                    if(empty($mokuai)){
                        $modular ="";
                        $dir = 'model';
                        $files = [
                            '__file__'   => [$name.".php"],
                        ];
                    }else{
                        $modular = $mokuai."\\";
                        $dir = $mokuai;
                        $files = [
                            '__dir__'    => ['model'],
                            'model'=>[$name]
                        ];
                    }
                    if(strstr($tablename, '中间表') || strstr($tablename, '关联表')){
                        //中间表
                        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'piovt.stub');
                        $content = str_replace(
                            [
                                '{%name%}',
                                '{%modular%}',
                            ],
                            [
                                $name,
                                $modular,
                            ],
                            $content
                        );
                        $Build = new \demo\MyBuild();
                        $Build->execute($dir, $files, $content);
                    }else{
                        //模型表
                        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'model.stub');
                        $content = str_replace(
                            [
                                '{%name%}',
                                '{%modular%}',
                                '{%binding_table%}',
                                '{%id%}',
                                '{%disuse%}',
                                '{%scope%}',
                                '{%json%}',
                                '{%readonly%}',
                                '{%time%}',
                            ],
                            [
                                $name,
                                $modular,
                                $table1,
                                $res['key'],
                                $res['disuse'],
                                $res['scope'],
                                $res['json'],
                                $res['readonly'],
                                $res['time'],
                            ],
                            $content
                        );
                    }
                }
            }
        }
        View::assign('content',$content);
        View::assign('type',1);
        return View::fetch('create_model_code');
    }
    /**
     * 创建模型文件
     */
    public function create_model_files1(){
        $data = input('param.');
        $mokuai = $data['mokuai'];
        $modelLayer = input('modelLayer');
        if(!empty($data['table'])){
            //一个模型文件
            $cls = $this->columns($data['table']);
            $res =  $this->timestamp($cls);
            $table = $data['table'];
            $table1 = $table;
            $name = $this->parseName($table, 1);
            if($modelLayer == 'model'){
                //数据层
                if(empty($mokuai)){
                    $modular ="";
                    $dir = 'model';
                    $files = [
                        '__file__'   => [$name.".php"],
                    ];
                }else{
                    $modular = $mokuai."\\";
                    $dir = $mokuai;
                    $files = [
                        '__dir__'    => ['model'],
                        'model'=>[$name]
                    ];
                }
                $tablename = $this->table($table);
                if(strstr($tablename, '中间表') || strstr($tablename, '关联表')){
                    //中间表
                    $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'piovt.stub');
                    $content = str_replace(
                        [
                            '{%name%}',
                            '{%modular%}',
                        ],
                        [
                            $name,
                            $modular,
                        ],
                        $content
                    );
                    $Build = new \demo\MyBuild();
                    $Build->execute($dir, $files, $content);
                }else{
                    //模型表
                    $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'model.stub');
                    $content = str_replace(
                        [
                            '{%name%}',
                            '{%modular%}',
                            '{%binding_table%}',
                            '{%id%}',
                            '{%disuse%}',
                            '{%scope%}',
                            '{%json%}',
                            '{%readonly%}',
                            '{%time%}',
                        ],
                        [
                            $name,
                            $modular,
                            $table1,
                            $res['key'],
                            $res['disuse'],
                            $res['scope'],
                            $res['json'],
                            $res['readonly'],
                            $res['time'],
                        ],
                        $content
                    );
                    $Build = new \demo\MyBuild();
                    $Build->execute($dir, $files, $content);
                }
                $this->success('创建数据层模型文件完成');
            }
        }
        else{
            //全部模型文件
            //代码
            $tables = $this->mysql_tables();
            if($modelLayer == 'model'){
                //数据层
                foreach ($tables as $v){
                    $cls = $this->columns($v['Name']);
                    $res =  $this->timestamp($cls);
                    $table = $v['Name'];
                    $table1 = $table;
                    $name = $this->parseName($table, 1);
                    $tablename = $this->table($v['Name']);
                    if(empty($mokuai)){
                        $modular ="";
                        $dir = 'model';
                        $files = [
                            '__file__'   => [$name.".php"],
                        ];
                    }else{
                        $modular = $mokuai."\\";
                        $dir = $mokuai;
                        $files = [
                            '__dir__'    => ['model'],
                            'model'=>[$name]
                        ];
                    }
                    if(strstr($tablename, '中间表') || strstr($tablename, '关联表')){
                        //中间表
                        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'piovt.stub');
                        $content = str_replace(
                            [
                                '{%name%}',
                                '{%modular%}',
                            ],
                            [
                                $name,
                                $modular,
                            ],
                            $content
                        );
                        $Build = new \demo\MyBuild();
                        $Build->execute($dir, $files, $content);
                    }else{
                        //模型表
                        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'model.stub');
                        $content = str_replace(
                            [
                                '{%name%}',
                                '{%modular%}',
                                '{%binding_table%}',
                                '{%id%}',
                                '{%disuse%}',
                                '{%scope%}',
                                '{%json%}',
                                '{%readonly%}',
                                '{%time%}',
                            ],
                            [
                                $name,
                                $modular,
                                $table1,
                                $res['key'],
                                $res['disuse'],
                                $res['scope'],
                                $res['json'],
                                $res['readonly'],
                                $res['time'],
                            ],
                            $content
                        );
                        $Build = new \demo\MyBuild();
                        $Build->execute($dir, $files, $content);
                    }
                }
                $this->success('创建所有表的数据层模型文件完成');
            }
        }
    }
    //模型设置替换字段
    public function timestamp($cls){
        $data = [];
        $disuse = $json = $scope = $type = $readonly = $time = "";
        foreach ($cls as $c){
            if(strstr($c['Comment'], '时间')){
                $type .= "'".$c['Field']."'=> 'timestamp:Y-m-d H:i:s',\n";
            }
            if(strstr($c['Comment'], '只读')){
                $readonly .= "'".$c['Field']."',";
            }
            if(strstr($c['Field'], 'time')){
                $time .= "'".$c['Field']."',";
            }
            if($c['Key']=='PRI'){
                $data['key'] = $c['Field'];
            }else if(strstr($c['Comment'], '添加时间') || strstr($c['Comment'], '创建时间') || strstr($c['Comment'], '新增时间')){
                $data['addtime'] = $c['Field'];
            }else if(strstr($c['Comment'], '修改时间')){
                $data['savetime'] = $c['Field'];
            }else if(strstr($c['Comment'], '软删除')){
                $data['issoftdelete'] = $c['Field'];
            }else if($c['Type'] == "datetime" || $c['Type'] == "timestamp"){
                $data['time'][] = [
                    'Field' => $c['Field'],
                    'type' => $c['Type'],
                ];
            }else if(strstr($c['Comment'], '废弃')){
                $disuse .= "'".$c['Field']."',";
            }else if(strstr($c['Comment'], '范围')){
                $scope .= "'".$c['Field']."',";
            }else if(strstr($c['Comment'], 'json')){
                $json .= "'".$c['Field']."',";
            }
        }
        $data['disuse'] = substr($disuse,0,strlen($disuse)-1);
        $data['json'] = substr($json,0,strlen($json)-1);
        $data['scope'] = substr($scope,0,strlen($scope)-1);
        $data['type'] = $type;
        $data['readonly'] = substr($readonly,0,strlen($readonly)-1);
        $data['time'] = substr($time,0,strlen($time)-1);

        return $data;
    }
    /**
     * 创建模型文件
     * @return string
     * @throws \Exception
     */
    public function create_model_files(){
        View::assign('mokuai',$this->mokuai());
        View::assign('tables',$this->mysql_tables());
        return View::fetch();
    }

    /**
     * 验证器信息页面
     * @return string
     * @throws \Exception
     */
    public function validata_page3(){
        $vals = input('param.');
        $cls = $this->columns($vals['table']);
        $data = $this->validata($cls,$vals);
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'validate.stub');
        $name = Str::title($vals['validata_name']);

        $fields = "";
        if(empty($data['ss'])){
            foreach($cls as $c){
                if($c['Key'] != 'PRI'){
                    $fields.= "'".$c['Field']."',";
                }
            }
            $fields = trim($fields,',');
        }
        else{
            foreach($data['ss'] as $c){
                $fields.= "'".$c."',";
            }
            $fields = trim($fields,',');
        }

        $rs = '';
        foreach ($data['rs'] as $k=>$v){
            $rs .= "    '{$k}'  " ."  => '".implode('|',$v)."',\r            ";
        }
        $ms = '';
        foreach ($data['ms'] as $k=>$v){
            $ms .= "    '{$k}'  " ."  => '".$v."',\r        ";
        }
        $content = str_replace(
            ['{%name%}','{%rule%}','{%message%}','{%fields%}'],
            [$name, $rs, $ms,$fields],
            $content
        );
        if($vals['is_code'] == 2){
            //生成验证器文件
            $dir = 'validate';
            $files = [
                '__file__'   => [$name.".php"],
            ];
            $Build = new \demo\MyBuild();
            $Build->execute($dir, $files, $content);
            $this->success('验证器文件创建完成');
        }
        else{
            View::assign('content',$content);
            return View::fetch();
        }
    }

    /**
     * 验证器信息页面
     * @return string
     * @throws \Exception
     */
    public function validata_page2(){
        $name = input("validata_name");
        View::assign('validata_name',$name);
        $table = input("table");
        if($table!=''){
            $cls = $this->columns($table);
            View::assign('cls',$cls);
        }
        return View::fetch();
    }
    /**
     * 验证器页面
     * @return string
     * @throws \Exception
     */
    public function validata_page(){
        $tbs = $this->mysql_tables();
        View::assign('tables',$tbs);
        return View::fetch();
    }

    /**
     * 组装验证器数据
     * @param $c
     * @return mixed
     */
    private function _getf($c){
        if($c['Comment']!=''){
            return $c['Comment'];
        }else
            return $c['Field'];
    }
    /**
     * 组装验证器数据
     * @param $k
     * @param $name
     * @param $value
     * @return string
     */
    private function _name($k, $name, $value){
        if(empty($name)){
            $data = $this->_getf($k).$value;
        }else{
            $data = $name .$value;
        }
        return $data;
    }

    /**
     * 组装验证器数据
     * @param $cls
     * @param $vals
     * @return array
     */
    public function validata($cls,$vals){
        $ms = array();
        $rs = array();
        $ss = array();
        for($k=0;$k<count($cls);$k++){
            $c = $cls[$k]['Field'];
            if(isset($vals[$c])){
                if($vals[$c]=='on'){
                    $ss[] = $c;
                }
            }
            if(isset($vals[$c.'_'.'require'])){
                if($vals[$c.'_'.'require']=='on'){
                    $rs[$c][]='require';
                    $ms[$c.'.require'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'必填');
                }
            }
            if(isset($vals[$c.'_'.'number'])){
                if($vals[$c.'_'.'number']=='on'){
                    $rs[$c][]='number';
                    $ms[$c.'.number'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为数字');
                }
            }
            if(isset($vals[$c.'_'.'float'])){
                if($vals[$c.'_'.'float']=='on'){
                    $rs[$c][]='float';
                    $ms[$c.'.float'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为小数');
                }
            }
            if(isset($vals[$c.'_'.'boolean'])){
                if($vals[$c.'_'.'boolean']=='on'){
                    $rs[$c][]='boolean';
                    $ms[$c.'.boolean'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为布尔');
                }
            }
            if(isset($vals[$c.'_'.'email'])){
                if($vals[$c.'_'.'email']=='on'){
                    $rs[$c][]='email';
                    $ms[$c.'.email'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为邮箱格式');
                }
            }
            if(isset($vals[$c.'_'.'accepted'])){
                if($vals[$c.'_'.'accepted']=='on'){
                    $rs[$c][]='accepted';
                    $ms[$c.'.accepted'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为是和否');
                }
            }
            if(isset($vals[$c.'_'.'date'])){
                if($vals[$c.'_'.'date']=='on'){
                    $rs[$c][]='date';
                    $ms[$c.'.date'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为日期');
                }
            }
            if(isset($vals[$c.'_'.'alpha'])){
                if($vals[$c.'_'.'alpha']=='on'){
                    $rs[$c][]='alpha';
                    $ms[$c.'.alpha'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为字母');
                }
            }
            if(isset($vals[$c.'_'.'array'])){
                if($vals[$c.'_'.'array']=='on'){
                    $rs[$c][]='array';
                    $ms[$c.'.array'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为数组');
                }
            }
            if(isset($vals[$c.'_'.'alphaNum'])){
                if($vals[$c.'_'.'alphaNum']=='on'){
                    $rs[$c][]='alphaNum';
                    $ms[$c.'.alphaNum'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为字母数字');
                }
            }
            if(isset($vals[$c.'_'.'alphaDash'])){
                if($vals[$c.'_'.'alphaDash']=='on'){
                    $rs[$c][]='alphaDash';
                    $ms[$c.'.alphaDash'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为字母数字下划线等');

                }
            }
            if(isset($vals[$c.'_'.'activeUrl'])){
                if($vals[$c.'_'.'activeUrl']=='on'){
                    $rs[$c][]='activeUrl';
                    $ms[$c.'.activeUrl'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为域名/IP');

                }
            }
            if(isset($vals[$c.'_'.'url'])){
                if($vals[$c.'_'.'url']=='on'){
                    $rs[$c][]='url';
                    $ms[$c.'.url'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为URL');
                }
            }
            if(isset($vals[$c.'_'.'ip'])){
                if($vals[$c.'_'.'ip']=='on'){
                    $rs[$c][]='ip';
                    $ms[$c.'.ip'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为ip');

                }
            }
            if(isset($vals[$c.'_'.'phone'])){
                if($vals[$c.'_'.'phone']=='on'){
                    $rs[$c][]='regex:/^1[345789]\d{9}$/';
                    $ms[$c.'.phone'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为手机号格式');
                }
            }
            if(isset($vals[$c.'_'.'shen'])){
                if($vals[$c.'_'.'shen']=='on'){
                    $rs[$c][]='regex:/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/i';
                    $ms[$c.'.shen'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'为身份证格式');
                }
            }
            if(isset($vals[$c.'_'.'regex'])){
                if($vals[$c.'_'.'regex']!=''){
                    $rs[$c][]='regex:'.$vals[$c.'_'.'regex'];
                    $ms[$c.'.regex'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'无法通过验证');
                }
            }
            if(isset($vals[$c.'_'.'confirm'])){
                if($vals[$c.'_'.'confirm']!=''){
                    $rs[$c][]='confirm:'.$vals[$c.'_'.'confirm'];
                    $ms[$c.'.confirm'] = $this->_name($cls[$k],'和'.$vals[$c.'_'.'confirm'],'不一致');
                }
            }
            if(isset($vals[$c.'_'.'max'])){
                if($vals[$c.'_'.'max']!=''){
                    $rs[$c][]='max:'.$vals[$c.'_'.'max'];
                    $ms[$c.'.max'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'最大值为'.$vals[$c.'_'.'max']);

                }
            }
            if(isset($vals[$c.'_'.'min'])){
                if($vals[$c.'_'.'min']!=''){
                    $rs[$c][]='min:'.$vals[$c.'_'.'min'];
                    $ms[$c.'.min'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'最小值为'.$vals[$c.'_'.'min']);
                }
            }
            if(isset($vals[$c.'_'.'before'])){
                if($vals[$c.'_'.'before']!=''){
                    $rs[$c][]='before:'.$vals[$c.'_'.'before'];
                    $ms[$c.'.before'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'必须在'.$vals[$c.'_'.'before'].'之前');
                }
            }
            if(isset($vals[$c.'_'.'after'])){
                if($vals[$c.'_'.'after']!=''){
                    $rs[$c][]='after:'.$vals[$c.'_'.'after'];
                    $ms[$c.'.after'] = $this->_name($cls[$k],$vals[$c.'_'.'name'],'必须在'.$vals[$c.'_'.'before'].'之后');
                }
            }
        }
        $data = [
            'rs' => $rs,
            'ms' => $ms,
            'ss' => $ss,
        ];
        return $data;
    }

    /**
     * 创建事件文件
     * @return string
     * @throws \Exception
     */
    public function create_event(){
        $data = input('param.');
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'event.stub');
        $name = Str::title($data['event_name']);
        //创建事件文件
        $dir = 'event';
        $files = [
            '__file__'    => [$name.".php"],
        ];
        $msg = '创建事件文件成功！';
        $content = str_replace(
            ['{%name%}'],
            [$name],
            $content
        );
        $Build = new \demo\MyBuild();
        $Build->execute($dir, $files, $content);

        //创建事件监听器文件
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'listener.stub');
        $dir = 'listener';
        $files = [
            '__file__'    => [$name.".php"],
        ];
        $msg .= '创建事件监听器文件成功！';
        $content = str_replace(
            ['{%name%}'],
            [$name],
            $content
        );
        $Build->execute($dir, $files, $content);

        //创建事件订阅文件
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'subscribe.stub');
        $dir = 'subscribe';
        $files = [
            '__file__'    => [$name.".php"],
        ];
        $msg .= '创建事件订阅文件成功！';
        $content = str_replace(
            ['{%name%}'],
            [$name],
            $content
        );
        $Build->execute($dir, $files, $content);
        $this->success($msg);
    }

    /**
     * 事件代码
     * @return string
     * @throws \Exception
     */
    public function event_code(){
        $data = input('param.');
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'event.stub');
        $name = Str::title($data['event_name']);
        $content = str_replace(
            ['{%name%}'],
            [$name],
            $content
        );
        View::assign('event_name',$name);
        View::assign('content',$content);
        View::assign('code',true);
        return View::fetch('event_page');
    }

    /**
     * 事件页面
     * @return string
     * @throws \Exception
     */
    public function event_page(){
        return View::fetch();
    }

    /**
     * 创建中间件文件
     * @return string
     * @throws \Exception
     */
    public function create_middleware(){
        $data = input('param.');
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'middleware.stub');
        $name = Str::title($data['middleware_name']);
        if($data['modular']){
            $modular = $data['modular']."\\";
            $dir = $data['modular'];
            $files = [
                '__dir__'    => ['middleware'],
                'middleware'=>[$name]
            ];
            $msg = '生成多应用中间件文件成功';
        }else{
            $modular = "";
            $dir = 'middleware';
            $files = [
                '__file__'    => [$name.".php"],
            ];
            $msg = '生成全局中间件文件成功';
        }
        $content = str_replace(
            ['{%name%}','{%modular%}'],
            [$name,$modular],
            $content
        );
        $Build = new \demo\MyBuild();
        $Build->execute($dir, $files, $content);
        $this->success($msg);
    }

    /**
     * 中间件代码
     * @return string
     * @throws \Exception
     */
    public function middleware_code(){
        $data = input('param.');
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'middleware.stub');
        $name = Str::title($data['middleware_name']);
        if($data['modular']){
            $modular = $data['modular']."\\";
        }else{
            $modular = "";
        }
        $content = str_replace(
            ['{%name%}','{%modular%}'],
            [$name,$modular],
            $content
        );
        View::assign('middleware_name',$name);
        View::assign('modular',$data['modular']);
        View::assign('content',$content);
        View::assign('code',true);
        return View::fetch('middleware_page');
    }

    /**
     * 中间件页面
     * @return string
     * @throws \Exception
     */
    public function middleware_page(){
        return View::fetch();
    }

    /**
     * 公共函数文件页面
     * @return string
     * @throws \Exception
     */
    public function common_page(){
        $content = file_get_contents($this->app->getBasePath() . 'code\stubs' . DIRECTORY_SEPARATOR . 'common.stub');
        View::assign('content',$content);
        return View::fetch();
    }

    /**
     * 首页
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 模块页面
     * @return string
     * @throws \Exception
     */
    public function modular_page(){

        return View::fetch();
    }

    /**
     * 自动创建模块
     */
    public function create_modular()
    {
        $input = input("param.");
        $data =  include $this->app->getBasePath() . 'build.php';
        $Build = new \demo\MyBuild();
        $Build->execute($input['modular_name'],$data);
        $this->success("生成模块目录及文件成功");
    }



    /**
     *
     * 数据库内容获取
     * @return array
     */

    /**
     * 查询数据库所有表信息
     * @return array
     */
    protected function mysql_tables()
    {
        $tables = Db::query('show table status');
        return $tables;
    }
    //查询表信息
    public function table($table){
        $database = config('database.connections.mysql.database');
        $res = Db::query("select table_comment from information_schema.tables where table_schema = '$database' and table_name ='$table'");
        return $res[0]['table_comment'];
    }
    //查询表中所有字段信息
    protected function columns($table){
        $columns = Db::query("SHOW FULL COLUMNS FROM ".$table);
        return $columns;
    }
    //生成文件的数据
    public function modelbuild($mokuai,$modelLayer,$table = null){
        $data = [
            '__dir__' => [$modelLayer],
            "$modelLayer"  => [$table],
        ];
        return $data;
    }
    //获取模型
    public function controller_step2(){
        $mokuai = input('mokuai');
        if(empty($mokuai)){
            return false;
        }
        $dir1 = dirname(dirname(dirname(__FILE__))).'\\'.$mokuai."\\logic";
        $files = array();
        if(is_dir($dir1)){
            $child_dirs = scandir($dir1);
            foreach($child_dirs as $child_dir){
                if(strstr($child_dir, '.php')){
                    $files['logic'][] = basename($child_dir,".php");
                }
            }
        }
        return json($files);
    }
    //获取模块
    public function mokuai(){
        $dir = dirname(dirname(dirname(__FILE__)));
        $files = array();
        if(is_dir($dir)){
            $child_dirs = scandir($dir);
            foreach($child_dirs as $child_dir){
                if($child_dir != '.' && $child_dir != '..' && $child_dir != "extra" && !strstr($child_dir, '.')){
                    $files[] = $child_dir;
                }
            }
        }
        foreach( $files as $k=>$v) {
            if('code' == $v || 'event' == $v || 'validate' == $v || 'listener' == $v || 'middleware' == $v || 'subscribe' == $v){
                unset($files[$k]);
            }
        }
        return $files;
    }

    //数据表名转换成符合命名规格的字符串
    public static function parseName($name, $type = 0, $ucfirst = true)
    {
        if(!empty(config('database.connections.mysql.prefix'))){
            $count=strpos($name,config('database.connections.mysql.prefix'));
            $name=substr_replace($name,"",$count,strlen(config('database.connections.mysql.prefix')));
        }
        if ($type) {
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name);
            return $ucfirst ? ucfirst($name) : lcfirst($name);
        }

        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
    }
}
